<?php
header("Content-Type:text/xml; charset=UTF-8");
class CheckController extends Controller {

    public function actionList() {
        $data = trim(file_get_contents("php://input"));
        $totalPremium = 0;
        $data = $this->validateData($data);
        $isInsure = $data['isInsure'];
        $page = $data['page'] > 0?$data['page']:1;
        //获取所有产品的信息
        $res = CsProductCode::model()->findAll();
        $products = array();
        foreach ($res as $val) {
            $products[$val->third_party_code][$val->in_company] = $val->premium;
        }
        $resInsure = $resSurrender = array('totalPremium'=>0,'insure'=>array());
        unset($res);
        if ($isInsure == 1) {
            $resInsure = $this->insure($data['startTime'],$data['endTime'],$data['policyCode'],$products,$page);
            $count = count($resInsure['data']);
            $totalPremium = $resInsure['totalPremium'];
            $totalPage = $resInsure['totalPage'];
            $page = $resInsure['page'];
            $data = $resInsure['data'];
        }
        if ($isInsure == 2) {
            $resSurrender = $this->surrender($data['startTime'],$data['endTime'],$data['policyCode'],$products,$page);
            $count = count($resSurrender['data']);
            $totalPremium = $resSurrender['totalPremium'];
            $totalPage = $resSurrender['totalPage'];
            $page = $resSurrender['page'];
            $data = $resSurrender['data'];
        }
        /*
        if ($isInsure == 3) {
            $resInsure = $this->insure($data['startTime'],$data['endTime'],$data['policyCode'],$products,$page);
            $resSurrender = $this->surrender($data['startTime'],$data['endTime'],$data['policyCode'],$products,$page);
            $totalPremium = ($resInsure['totalPremium'] + $resSurrender['totalPremium']);
            $count = count($resInsure['data']) + count($resSurrender['data']);
            $data = $resInsure['data'];
            foreach ($resSurrender['data'] as $value) {
                $data[] = $value;
            }
        }*/
        if ($data) {
            $Insurance = "";
            foreach ($data as $value) {
                $Insurance .= "
                    <Insurance>
                    <tcSerialNo>".$value['tcSerialNo']."</tcSerialNo>
                    <updated>".$value['updated']."</updated >
                    <applicantName>".$value['applicantName']."</applicantName>
                    <policyNum>".$value['policyNum']."</policyNum>
                    <status>".$value['status']."</status>
                    <planCode>".$value['planCode']."</planCode>
                    <premium>".$value['premium']."</premium>
                    </Insurance>";
            }
            $xml_content = '<?xml version="1.0" encoding="utf-8" ?>
            <rlt>
                <st>1</st>
                <InsuranceList>
                    <total_page>'.$totalPage.'</total_page>
                    <curr_page>'.$page.'</curr_page>
                    <count>'.$count.'</count>
                    <totalPremium>'.$totalPremium.'</totalPremium>
                    <details>'.$Insurance.'</details>
                </InsuranceList>
            </rlt>';
        } else {
            $xml_content = '<?xml version="1.0" encoding="utf-8" ?>
            <rlt>
                <St>1</St>
                <count>0</count>
                <totalPremium >0</totalPremium>
                <InsuranceList>
                <details></details>
                </InsuranceList>
            </rlt>';
        }
        echo $xml_content;
    }

    //查看投保成功数目
    private function insure($startTime,$endTime,$policyCode=null,$products,$page=1) {
        $t1 = microtime(true);
        $this->log("获取投保数据、开始时间：".$t1.'毫秒');
        $totalPremium = 0;
        $connection = Yii::app()->db;
        $countSql = "select count(id) as count from cs_xc_importinfo where retCode = '00' and createTime >= $startTime and createTime <= $endTime";
        $command = $connection->createCommand($countSql);
        $countArr = $command->queryAll();
        $count = $countArr[0]['count'];
        if (Yii::app()->params['limit']) {
            $limit = Yii::app()->params['limit'];
        } else {
            $limit = 1000;
        }
        $totalPage = ceil($count / $limit);
        $limitSql = " limit ".($page - 1)*$limit.", $limit";
        $sql = "select approvaltrans_id,cWaterNo,policyNum,realDate,createTime,in_company from cs_xc_importinfo where retCode = '00' and createTime >= $startTime and createTime <= $endTime";
        $sql .= $limitSql;
        $command = $connection->createCommand($sql);
        $result = $command->queryAll();
        foreach ($result as $value) {
            $approvaltrans_id = $value['approvaltrans_id'];
            $ProductCode = null;
            $sql = "select ProductCode from cs_approvaltrans where id = $approvaltrans_id";
            $command = $connection->createCommand($sql);
            $res = $command->queryAll();
            if ($res) {
                $ProductCode = $res[0]['ProductCode'];
            }
            if ($policyCode) {
                if ($policyCode != $ProductCode) {
                     continue;
                }
            }
            if ($ProductCode == null) {
                continue;
            }
            $insured = InsuredinfoF::model()->findByAttributes(array('approvaltrans_id'=>$value['approvaltrans_id']));
            $time = $value['realDate']?$value['realDate']:$value['createTime'];
            $data[] = array(
                'tcSerialNo' => $value['cWaterNo'],  //流水号
                'updated' => date('Y-m-d H:i:s',$time),  //投(退)保时间
                'applicantName' => $insured->InsuedName, //被保人姓名
                'policyNum' => $value['policyNum'],   //保单号
                'status' => 1,
                'planCode' => $ProductCode,
                'premium' => $products[$ProductCode][$value['in_company']]
            );
            $totalPremium += $products[$ProductCode][$value['in_company']];
        }
        $t2 = microtime(true);
        $this->log("获取投保数据、结束时间：".$t2.'毫秒');
        $this->log("获取投保数据、消耗时间：".round($t2-$t1,3).'秒');
        return array(
            'totalPremium' => $totalPremium,
            'data' => $data,
            'totalPage' => $totalPage,
            'page' => $page
        );

    }

    //查看退保成功数目
    private function surrender($startTime,$endTime,$policyCode=null,$products,$page=1) {
        $t1 = microtime(true);
        $this->log("获取退保数据、开始时间：".$t1.'毫秒');
        $totalPremium = 0;
        $connection = Yii::app()->db;

        $countSql = "select count(id) as count from cs_surrenderinfo where retCode = '00' and createTime >= $startTime and createTime <= $endTime";
        $command = $connection->createCommand($countSql);
        $countArr = $command->queryAll();
        $count = $countArr[0]['count'];
        if (Yii::app()->params['limit']) {
            $limit = Yii::app()->params['limit'];
        } else {
            $limit = 1000;
        }
        $totalPage = ceil($count / $limit);
        $limitSql = " limit ".($page - 1)*$limit.", $limit";
        $sql = "select surrender_id,waterNo,policyNo,realDate,createTime,in_company from cs_surrenderinfo where retCode = '00' and createTime >= $startTime and createTime <= $endTime";
        $sql .= $limitSql;
        $command = $connection->createCommand($sql);
        $result = $command->queryAll();
        foreach ($result as $value) {
            $surrender_id = $value['surrender_id'];
            $ProductCode = null;
            $sql = "select productCode from cs_surrender where id = $surrender_id";
            $command = $connection->createCommand($sql);
            $res = $command->queryAll();
            if ($res) {
                $ProductCode = $res[0]['productCode'];
            }
            if ($policyCode) {
                if ($policyCode != $ProductCode) {
                    continue;
                }
            }
            if ($ProductCode == null) {
                continue;
            }
            $model = ImportinfoF::model()->findByAttributes(array('policyNum'=>$value['policyNo']));
            $insured = InsuredinfoF::model()->findByAttributes(array('approvaltrans_id'=>$model->approvaltrans_id));
            $time = $value['realDate']?$value['realDate']:$value['createTime'];
            $data[] = array(
                'tcSerialNo' => $value['waterNo'],  //流水号
                'updated' => date('Y-m-d H:i:s',$time),  //投(退)保时间
                'applicantName' => $insured->InsuedName, //被保人姓名
                'policyNum' => $value['policyNo'],   //保单号
                'status' => 2,
                'planCode' => $ProductCode,
                'premium' => $products[$ProductCode][$value['in_company']]
            );
            $totalPremium += $products[$ProductCode][$value['in_company']];
        }
        $t2 = microtime(true);
        $this->log("获取退保数据、结束时间：".$t2.'毫秒');
        $this->log("获取退保数据、消耗时间：".round($t2-$t1,3).'秒');
        return array(
            'totalPremium' => $totalPremium,
            'data' => $data,
            'totalPage' => $totalPage,
            'page' => $page
        );
    }

    //验证入参
    private function validateData($data) {
        if (empty($data)) {
            echo $xml_content = '<?xml version="1.0" encoding="utf-8"?>
            <rlt>
                <st>101</st>
                <errInfo>无参数</errInfo>
            </rlt>';
            die();
        }
        $this->log("对账请求报文：".$data);
        $xml_parser = xml_parser_create();
        if(!xml_parse($xml_parser,$data,true)){
            xml_parser_free($xml_parser);
            echo $xml_content = '<?xml version="1.0" encoding="utf-8"?>
            <rlt>
                <st>101</st>
                <errInfo>参数错误</errInfo>
            </rlt>';
            die();
        }
        $data = simplexml_load_string($data);
        $data = json_decode(json_encode((array) $data), true);

        if ($data['trasinf']['service'] != 'GetInsuranceInfo') {
            echo $xml_content = '<?xml version="1.0" encoding="utf-8"?>
            <rlt>
                <st>101</st>
                <errInfo>service错误</errInfo>
            </rlt>';
            die();
        }
        if (!strtotime($data['ucom']['startTime']) || !strtotime($data['ucom']['endTime']) || (strtotime($data['ucom']['startTime']) > strtotime($data['ucom']['endTime']))) {
            echo $xml_content = '<?xml version="1.0" encoding="utf-8"?>
            <rlt>
                <st>101</st>
                <errInfo>时间格式出错</errInfo>
            </rlt>';
            die();
        }
        if ($data['ucom']['policyCode']) {
            $third_party_code = $data['ucom']['policyCode'];
            $model = CsProductCode::model()->findByAttributes(array("third_party_code"=>$third_party_code));
            if (!$model) {
                echo $xml_content = '<?xml version="1.0" encoding="utf-8"?>
            <rlt>
                <st>101</st>
                <errInfo>产品不存在</errInfo>
            </rlt>';
                die();
            }
        }
        if (!in_array($data['ucom']['isInsure'],array(1,2))) {
            echo $xml_content = '<?xml version="1.0" encoding="utf-8"?>
            <rlt>
                <st>101</st>
                <errInfo>isInsure入参错误,暂只接受1、2</errInfo>
            </rlt>';
            die();
        }
        $data['ucom']['startTime'] = strtotime(date('Y-m-d',strtotime($data['ucom']['startTime'])).'00:00:00');
        $data['ucom']['endTime'] = strtotime(date('Y-m-d',strtotime('+1 day '.$data['ucom']['endTime'])).'00:00:00');

        return $data['ucom'];
    }

    //日志
    private function log($content) {
        $path = "log/".date("Y-m-d");
        if (!file_exists($path)) {
            mkdir($path);
        }
        $path .= "/duizhang.log";
        $open=fopen($path,"a");
        fwrite($open,date('Y-m-d H:i:s').':'.$content."\r\n");
        fclose($open);
    }
}